
package org.snail.common;


import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 重命名线程,用于监控
 * @author fish
 */
public class SnailThreadFactory implements ThreadFactory {

    private static final InternalLogger logger = InternalLoggerFactory.getInstance(SnailThreadFactory.class);

    private final AtomicInteger id = new AtomicInteger();
    private final String name;
    private final boolean daemon;
    private final int priority;
    private final ThreadGroup group;

    public SnailThreadFactory(String name) {
        this(name, false, Thread.NORM_PRIORITY);
    }

    public SnailThreadFactory(String name, boolean daemon) {
        this(name, daemon, Thread.NORM_PRIORITY);
    }

    public SnailThreadFactory(String name, int priority) {
        this(name, false, priority);
    }

    public SnailThreadFactory(String name, boolean daemon, int priority) {
        this.name = name + " #";
        this.daemon = daemon;
        this.priority = priority;
        SecurityManager securityManager = System.getSecurityManager();
        group = (securityManager == null) ? Thread.currentThread().getThreadGroup() : securityManager.getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable runnable) {
        String rename = name + id.getAndIncrement();
        Thread thread = new Thread(group, runnable, rename);
        try {
            if (thread.isDaemon() != daemon) {
                thread.setDaemon(daemon);
            }

            if (thread.getPriority() != priority) {
                thread.setPriority(priority);
            }
        } catch (Exception ignored) { /* doesn't matter even if failed to set. */ }

        logger.debug("Creates new {}.", thread);

        return thread;
    }

    public ThreadGroup getThreadGroup() {
        return group;
    }
}
